package cn.mujiankeji.mbrowser.界面.小窗页.广告拦截

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.功能.广告拦截.项目.广告拦截订阅文件简介信息
import cn.mujiankeji.mbrowser.界面.图标.MyIconPack
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.暂停
import cn.mujiankeji.mbrowser.界面.组件.布局.IOS窗口布局
import java.text.SimpleDateFormat
import java.util.*

/**
 * 广告拦截规则管理窗口
 * 
 * @param 状态 窗口状态对象
 */
@Composable
fun 广告拦截规则管理窗口(状态: 广告拦截规则管理窗口状态) {
    // 设置协程作用域
    状态.coroutine = rememberCoroutineScope()
    
    // 初始化状态
    LaunchedEffect(Unit) {
        状态.初始化()
    }
    
    IOS窗口布局(
        标题 = "广告拦截规则管理",
        销毁 = { 状态.销毁小窗() }
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // 顶部标签栏
            顶部标签栏(状态)
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 内容区域
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                when (状态.当前标签页) {
                    0 -> 订阅规则标签页(状态)
                    1 -> 自定义规则标签页(状态)
                }
                
                // 加载中指示器
                if (状态.正在加载) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black.copy(alpha = 0.3f)),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                }
            }
        }
    }
}

/**
 * 顶部标签栏
 */
@Composable
private fun 顶部标签栏(状态: 广告拦截规则管理窗口状态) {
    TabRow(
        selectedTabIndex = 状态.当前标签页,
        modifier = Modifier.fillMaxWidth()
    ) {
        Tab(
            selected = 状态.当前标签页 == 0,
            onClick = { 状态.当前标签页 = 0 },
            text = { Text("订阅规则") }
        )
        Tab(
            selected = 状态.当前标签页 == 1,
            onClick = { 状态.当前标签页 = 1 },
            text = { Text("自定义规则") }
        )
    }
}

/**
 * 订阅规则标签页
 */
@Composable
private fun 订阅规则标签页(状态: 广告拦截规则管理窗口状态) {
    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        // 添加规则输入框
        添加规则输入框(状态)
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 订阅规则列表
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            items(状态.规则订阅列表) { 规则 ->
                规则订阅项(规则, 状态)
            }
            
            // 空列表提示
            if (状态.规则订阅列表.isEmpty()) {
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "没有订阅规则\n可通过顶部输入框添加规则URL",
                            textAlign = TextAlign.Center,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
        
        // 错误信息
        状态.加载错误信息?.let { 错误信息 ->
            Text(
                text = 错误信息,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
            )
        }
    }
}

/**
 * 添加规则输入框
 */
@Composable
private fun 添加规则输入框(状态: 广告拦截规则管理窗口状态) {
    val focusRequester = remember { FocusRequester() }
    
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        OutlinedTextField(
            value = 状态.新规则URL,
            onValueChange = { 状态.新规则URL = it },
            label = { Text("输入规则URL") },
            modifier = Modifier
                .weight(1f)
                .focusRequester(focusRequester),
            singleLine = true,
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
            keyboardActions = KeyboardActions(onDone = { 状态.添加规则订阅() })
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        Button(
            onClick = { 状态.添加规则订阅() },
            enabled = !状态.正在加载
        ) {
            Text("添加")
        }
    }
}

/**
 * 规则订阅项
 */
@Composable
private fun 规则订阅项(规则: 广告拦截订阅文件简介信息, 状态: 广告拦截规则管理窗口状态) {
    var 显示删除确认 by remember { mutableStateOf(false) }
    var 显示规则详情 by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .clickable { 显示规则详情 = true },
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            // 规则名称与状态
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 启用状态指示器
                Box(
                    modifier = Modifier
                        .size(12.dp)
                        .background(
                            if (!规则.stop) MaterialTheme.colorScheme.primary
                            else MaterialTheme.colorScheme.surfaceVariant,
                            shape = RoundedCornerShape(50)
                        )
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                // 规则名称
                Text(
                    text = 规则.name,
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.weight(1f),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                
                // 规则条数
                Text(
                    text = "${规则.size}条",
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    style = MaterialTheme.typography.bodySmall
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 规则信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 更新时间
                if (规则.uptime > 0) {
                    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                    val 更新时间 = dateFormat.format(Date(规则.uptime))
                    
                    Text(
                        text = "更新: $更新时间",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.weight(1f)
                    )
                } else {
                    Spacer(modifier = Modifier.weight(1f))
                }
                
                // 操作按钮
                Row {
                    // 更新按钮
                    if (规则.upurl.isNotEmpty()) {
                        IconButton(
                            onClick = { 状态.更新规则订阅(规则) },
                            enabled = !状态.正在加载
                        ) {
                            Icon(
                                imageVector = Icons.Default.Refresh,
                                contentDescription = "更新规则",
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }
                    
                    // 启用/禁用按钮
                    IconButton(
                        onClick = { 状态.切换规则启用状态(规则) },
                        enabled = !状态.正在加载
                    ) {
                        Icon(
                            imageVector = if (规则.stop) Icons.Default.PlayArrow else MyIconPack.暂停,
                            contentDescription = if (规则.stop) "启用规则" else "禁用规则",
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                    
                    // 删除按钮
                    IconButton(
                        onClick = { 显示删除确认 = true },
                        enabled = !状态.正在加载
                    ) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = "删除规则",
                            tint = MaterialTheme.colorScheme.error
                        )
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    if (显示删除确认) {
        AlertDialog(
            onDismissRequest = { 显示删除确认 = false },
            title = { Text("删除规则") },
            text = { Text("确定要删除规则 \"${规则.name}\" 吗？") },
            confirmButton = {
                TextButton(
                    onClick = {
                        显示删除确认 = false
                        状态.删除规则订阅(规则)
                    }
                ) {
                    Text("删除", color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(onClick = { 显示删除确认 = false }) {
                    Text("取消")
                }
            }
        )
    }
    
    // 规则详情对话框
    if (显示规则详情) {
        AlertDialog(
            onDismissRequest = { 显示规则详情 = false },
            title = { Text("规则详情") },
            text = {
                Column {
                    Text("名称: ${规则.name}")
                    Spacer(modifier = Modifier.height(4.dp))
                    Text("规则数量: ${规则.size}条")
                    Spacer(modifier = Modifier.height(4.dp))
                    Text("状态: ${if (规则.stop) "已停用" else "已启用"}")
                    
                    if (规则.upurl.isNotEmpty()) {
                        Spacer(modifier = Modifier.height(4.dp))
                        Text("更新地址:")
                        Spacer(modifier = Modifier.height(2.dp))
                        Text(
                            text = 规则.upurl,
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                    
                    if (规则.uptime > 0) {
                        Spacer(modifier = Modifier.height(4.dp))
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
                        val 更新时间 = dateFormat.format(Date(规则.uptime))
                        Text("更新时间: $更新时间")
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { 显示规则详情 = false }) {
                    Text("关闭")
                }
            }
        )
    }
}

/**
 * 自定义规则标签页
 */
@Composable
private fun 自定义规则标签页(状态: 广告拦截规则管理窗口状态) {
    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        Text(
            text = "自定义规则",
            style = MaterialTheme.typography.titleMedium,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        
        Text(
            text = "每行一条规则，支持Adblock Plus格式",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        
        // 规则文本编辑框
        OutlinedTextField(
            value = 状态.自定义规则文本,
            onValueChange = { 状态.自定义规则文本 = it },
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .border(
                    width = 1.dp,
                    color = MaterialTheme.colorScheme.outline,
                    shape = RoundedCornerShape(4.dp)
                ),
            placeholder = { Text("在此输入自定义拦截规则，每行一条") }
        )
        
        // 错误信息
        状态.加载错误信息?.let { 错误信息 ->
            Text(
                text = 错误信息,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
            )
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 保存按钮
        Button(
            onClick = { 状态.保存自定义规则() },
            modifier = Modifier.align(Alignment.End),
            enabled = !状态.正在加载
        ) {
            Text("保存")
        }
    }
}

/**
 * 广告拦截规则管理窗口预览
 */
@Composable
fun 广告拦截规则管理窗口实现(状态: 广告拦截规则管理窗口状态) {
    广告拦截规则管理窗口(状态)
} 